import * as React from 'react';
import { Form, Select, Field, Input, Balloon, Badge } from '@teamix/ui';
import { YunxiaoIcon, ButtonIcon } from '@alife/devops-ui';
import { getCachedRepoValue } from 'utils/repoIdCache';
import MemberTrigger from 'components/memberTrigger';
import Popup from 'components/popup';
import track from 'utils/track';
import exceed from 'utils/apimap';
import PathEllipsis from 'components/pathEllipsis';
import utils from 'utils';
import isequal from 'lodash.isequal';
import intl from '../../locale';

const { user, pathResource } = window.FORCE;
const { Tooltip } = Balloon;

const userData = [
  {
    name: user.nickname || user.realName,
    _userId: user.id,
  },
];

const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    fixedSpan: 12,
  },
};

const maxTagPlaceholder = (selectedValues, totalValues) => {
  const trigger = <span>{`${selectedValues.length}/${totalValues.length}`}</span>;
  const labels = selectedValues.map((obj) => obj.label);
  return <Tooltip trigger={trigger}>{labels.join(', ')}</Tooltip>;
};

export default class AdvancedSearch extends React.Component {
  constructor(props) {
    super(props);
    this.field = new Field(this, {
      onChange: () => {
        this.dataTrack();
        this.setAdvancedSearchDataAndDoSearch();
      },
    });

    this.cacheKey = getCachedRepoValue('repo_user');

    this.state = {
      pageType: null,
      authorData: userData,
      couldChangeAuthor: true,
      assigneeData: userData,
      couldChangeAssignee: true,
      subscriberData: userData,
      repoDataSource: [],
      // 记录初始化的initFormValue，为了比较是否有过滤条件
      initFormValues: {},
    };
  }

  componentDidMount() {
    if (pathResource && pathResource.type === 'PROJECT') {
      this.setState(
        {
          pageType: 'project',
        },
        () => {
          this.resetFormByNavKeyAndTabkey();
        },
      );
    } else if (pathResource && pathResource.type === 'GROUP') {
      this.setState({
        pageType: 'group',
      });

      this.onGroupSubProjectList();
      this.resetFormByNavKeyAndTabkey();
    } else {
      this.setState({
        pageType: 'dashboard',
      });

      this.onProjectList();
      this.resetFormByNavKeyAndTabkey();
    }
  }

  dataTrack = () => {
    const { pageType } = this.state;
    if (pageType === 'project') {
      track({
        action: 'filter_mr',
        page: 'Repo-MRs',
      });
    } else if (pageType === 'group') {
      track({
        action: 'filter_mr',
        page: 'Group-MRs',
      });
    } else {
      track({
        action: 'filter_mr',
        page: 'Organization-MRs-All',
      });
    }
  };

  // navKey 或 tabKey 变化时，重置表单
  componentDidUpdate(prevProps) {
    if (this.props.addr !== 'pmr') {
      if (this.props.navKey !== prevProps.navKey || this.props.tabKey !== prevProps.tabKey) {
        this.resetFormByNavKeyAndTabkey();
      }
    }
  }

  // 获取表单数据，设置 advancedSearch，并触发查询
  setAdvancedSearchDataAndDoSearch = () => {
    this.field.validate((errors) => {
      if (!errors) {
        const formData = this.field.getValues();
        if (formData.author_tb_ids) {
          formData.author_tb_ids = formData.author_tb_ids.join(',');
        }
        if (this.state.pageType === 'project') {
          formData.project_ids = pathResource.id;
        } else if (this.state.pageType === 'group') {
          formData.group_ids = pathResource.id;
          if (formData.project_ids) {
            formData.project_ids = formData.project_ids.join(',');
          }
        } else {
          if (formData.project_ids) {
            formData.project_ids = formData.project_ids.join(',');
          }

          if (formData.group_ids) {
            formData.group_ids = formData.group_ids.join(',');
          }
        }
        if (formData.assignee_tb_ids) {
          formData.assignee_tb_ids = formData.assignee_tb_ids.join(',');
        }
        // if (formData.subscriber_tb_ids) {
        //   formData.subscriber_tb_ids = formData.subscriber_tb_ids.join(',');
        // }
        if (this.state.pageType === 'project') {
          const { authorData, assigneeData } = this.state;
          const formDataStr = JSON.stringify({
            authorData,
            assigneeData,
          });
          utils.setCachedData(`advanced-search-pagemr-${this.cacheKey}`, formDataStr);
        }
        this.props.setAdvancedSearch(formData);
      }
    });
  };

  // 根据 navKey 和 tabKey 重置表单
  resetFormByNavKeyAndTabkey = () => {
    const { navKey, tabKey } = this.props;
    let initFormValues;
    if (this.state.pageType === 'project') {
      const formDataStr = utils.getCachedData(`advanced-search-pagemr-${this.cacheKey}`);
      let formData = {
        authorData: [],
        assigneeData: [],
      };
      try {
        if (formDataStr) {
          formData = JSON.parse(formDataStr);
          formData.authorData = formData.authorData || [];
          formData.assigneeData = formData.assigneeData || [];
        }
        // eslint-disable-next-line no-empty
      } catch (err) {}
      initFormValues = {
        state: tabKey,
        project_ids: null,
        author_tb_ids: formData.authorData.map((v) => v._userId),
        assignee_tb_ids: formData.assigneeData.map((v) => v._userId),
      };
      this.field.setValues(initFormValues);
      this.setState(
        {
          authorData: formData.authorData,
          assigneeData: formData.assigneeData,
          subscriberData: [],
          initFormValues,
        },
        () => {
          this.setAdvancedSearchDataAndDoSearch();
        },
      );
    } else if (this.state.pageType === 'group') {
      initFormValues = {
        state: tabKey,
        project_ids: null,
        author_tb_ids: null,
        assignee_tb_ids: null,
        group_ids: null,
        // subscriber_ids: null,
      };
      this.field.setValues(initFormValues);
      this.setState({
        authorData: [],
        assigneeData: [],
        subscriberData: [],
        initFormValues,
      });
    } else {
      const ids = userData.map((item) => item._userId || item.tb_user_id);

      initFormValues = {
        state: tabKey,
        project_ids: null,
        author_tb_ids: navKey === 'created' ? ids : null,
        assignee_tb_ids: navKey === 'reviewed' ? ids : null,
        // subscriber_ids: navKey === 'cc' ? ids : null,
      };
      this.field.setValues(initFormValues);
      let curAuthorData = [];
      let curAssigneeData = [];
      let curSubscriberData = [];
      if (navKey === 'created') {
        curAuthorData = userData;
        this.setState({ couldChangeAuthor: false });
      } else {
        curAuthorData = [];
        this.setState({ couldChangeAuthor: true });
      }

      if (navKey === 'all') {
        if (this.state.authorData.length === 1 && this.state.authorData[0]._userId === user.id) {
          curAuthorData = [];
        } else {
          curAuthorData = this.state.authorData;
        }
      }

      if (navKey === 'reviewed') {
        curAssigneeData = userData;
        this.setState({ couldChangeAssignee: false });
      } else {
        curAssigneeData = [];
        this.setState({ couldChangeAssignee: true });
      }

      if (navKey === 'all') {
        if (
          this.state.assigneeData.length === 1 &&
          this.state.assigneeData[0]._userId === user.id
        ) {
          curAssigneeData = [];
        } else {
          curAssigneeData = this.state.assigneeData;
        }
      }

      if (navKey === 'cc') {
        curSubscriberData = this.state.subscriberData;
      }

      if (navKey === 'all') {
        if (
          this.state.subscriberData.length === 1 &&
          this.state.subscriberData[0]._userId === user.id
        ) {
          curSubscriberData = [];
        } else {
          curSubscriberData = this.state.subscriberData;
        }
      }

      this.setState({
        authorData: curAuthorData,
        assigneeData: curAssigneeData,
        subscriberData: curSubscriberData,
        initFormValues,
      });
    }
  };

  onAuthorChange = (value) => {
    this.setState(
      {
        authorData: value,
      },
      () => {
        this.field.setValue(
          'author_tb_ids',
          value.map((item) => item._userId),
        );
        this.setAdvancedSearchDataAndDoSearch();
      },
    );
  };

  onSubscriberChange = (value) => {
    this.setState({
      subscriberData: value,
    });

    this.field.setValue(
      'subscriber_tb_ids',
      value.map((item) => item._userId),
    );
    this.setAdvancedSearchDataAndDoSearch();
  };

  onAssigneeChange = (value) => {
    this.setState(
      {
        assigneeData: value,
      },
      () => {
        this.field.setValue(
          'assignee_tb_ids',
          value.map((item) => item._userId),
        );
        this.setAdvancedSearchDataAndDoSearch();
      },
    );
  };

  // 查询代码库，默认展示前5条
  onProjectList = (search, size = 5) => {
    exceed
      .fetch({
        api: 'projects.authorizedList',
        data: {
          contains_sub_projects: true,
          search,
          size,
          order_by: 'last_activity_at',
        },
      })
      .then((list) => {
        list.shift();
        const repoDataSource = [
          {
            label: intl.get({
              id: 'code-assets.components.crAdvancedSearch.LastUpdated',
              defaultMessage: '最近更新',
            }),
            children: [],
          },
        ];

        if (list && list.length) {
          repoDataSource[0].children.push(
            ...list.slice(0, size).map((project) => ({
              label: project.name,
              value: project.id,
              name_with_namespace: utils.getGroupPath(project.name_with_namespace),
            })),
          );
        }
        this.setState({
          repoDataSource,
        });
      });
  };

  // 查询组所有子代码库
  onGroupSubProjectList = (search, size = 5) => {
    exceed
      .fetch({
        api: 'groups.all.subprojects',
        data: {
          namespace_id: pathResource.id,
          search,
          size,
          order_by: 'last_activity_at',
        },
      })
      .then((list) => {
        list.shift();
        const repoDataSource = [
          {
            label: intl.get({
              id: 'code-assets.components.crAdvancedSearch.LastUpdated',
              defaultMessage: '最近更新',
            }),
            children: [],
          },
        ];

        if (list && list.length) {
          repoDataSource[0].children.push(
            ...list.slice(0, size).map((project) => ({
              label: project.name,
              value: project.id,
              name_with_namespace: utils.getGroupPath(project.name_with_namespace),
            })),
          );
        }
        this.setState({
          repoDataSource,
        });
      });
  };

  // 点击清除筛选表单内容返回到默认值
  onResetClick = () => {
    utils.setCachedData(`advanced-search-pagemr-${this.cacheKey}`, '');
    this.resetFormByNavKeyAndTabkey();
    this.setAdvancedSearchDataAndDoSearch();
  };

  getBadgeDot = () => {
    const { authorData, assigneeData, pageType } = this.state;
    if (pageType === 'project') {
      return !!(authorData.length + assigneeData.length);
    }
    const values = this.field.getValues();
    const { initFormValues } = this.state;
    if (!values) {
      return false;
    }
    return !isequal(values, initFormValues);
  };

  render() {
    const { field } = this;
    const { init } = field;
    const { pageType, repoDataSource } = this.state;

    const fullName =
      pathResource && pathResource.fullName ? pathResource.fullName.replace(' / ', '/') : '';
    const lastName = fullName.split('/').pop();
    const hasDot = this.getBadgeDot();

    return (
      <Popup
        trigger={
          <Badge dot={hasDot}>
            <ButtonIcon name="filter-line" />
          </Badge>
        }
        triggerType="click"
        footer={
          <Form.Item style={{ marginBottom: '0px' }}>
            <Form.Reset
              text
              type="primary"
              style={{ border: 0 }}
              onClick={this.onResetClick}
              toDefault
              className="advanced-search-form-btn"
            >
              <YunxiaoIcon type="delete-line" />
              {intl.get({
                id: 'code-assets.components.crAdvancedSearch.ClearAllFilterConditions',
                defaultMessage: '清除所有筛选条件',
              })}
            </Form.Reset>
          </Form.Item>
        }
      >
        <Form {...formItemLayout} labelTextAlign="left" field={field}>
          {pageType === 'group' ? (
            <Form.Item
              label={intl.get({
                id: 'code-assets.src.utils.locale.CodeGroup',
                defaultMessage: '代码组',
              })}
            >
              <Input readOnly disabled value={lastName || ''} />
            </Form.Item>
          ) : null}
          <Form.Item
            label={intl.get({
              id: 'code-assets.src.utils.locale.CodeBase',
              defaultMessage: '代码库',
            })}
          >
            {pageType === 'project' ? (
              <Input readOnly disabled value={lastName || ''} />
            ) : (
              <Select
                {...init('project_ids')}
                mode="multiple"
                showSearch
                followTrigger
                maxTagCount={4}
                placeholder={intl.get({
                  id: 'code-assets.src.utils.locale.EnterACodeLibraryName.1',
                  defaultMessage: '请输入代码库名以搜索',
                })}
                dataSource={repoDataSource}
                onSearch={(value) => {
                  this.dataTrack();
                  if (pageType === 'group') {
                    // 组内用搜子库接口
                    this.onGroupSubProjectList(value);
                  } else {
                    this.onProjectList(value);
                  }
                }}
                maxTagPlaceholder={maxTagPlaceholder}
                popupProps={{
                  className: 'at-path-select-popup',
                }}
                itemRender={(item) => {
                  const path = item.name_with_namespace;
                  return <PathEllipsis path={path} />;
                }}
              />
            )}
          </Form.Item>
          <Form.Item
            label={intl.get({
              id: 'code-assets.src.utils.locale.Founder',
              defaultMessage: '创建人',
            })}
          >
            {this.state.couldChangeAuthor ? (
              <div
                ref={(o) => {
                  this.aucontainer = o;
                }}
              >
                <MemberTrigger
                  noMore
                  onChange={(value) => {
                    this.dataTrack();
                    this.onAuthorChange(value);
                  }}
                  value={this.state.authorData}
                  container={() => this.aucontainer}
                  multiple
                />
              </div>
            ) : (
              <Input disabled value={this.state.authorData[0].name} />
            )}
          </Form.Item>
          <Form.Item
            label={intl.get({
              id: 'code-assets.src.utils.locale.Reviewer',
              defaultMessage: '评审人',
            })}
          >
            {this.state.couldChangeAssignee ? (
              <div
                ref={(d) => {
                  this.recontainer = d;
                }}
              >
                <MemberTrigger
                  onChange={(value) => {
                    this.dataTrack();
                    this.onAssigneeChange(value);
                  }}
                  value={this.state.assigneeData}
                  container={() => this.recontainer}
                  multiple
                />
              </div>
            ) : (
              <Input disabled value={this.state.assigneeData[0].name} />
            )}
          </Form.Item>
        </Form>
      </Popup>
    );
  }
}
